<?php
/**
 * 常用观众信息管理API
 * 为用户提供常用观众信息的增删改查功能
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 验证token（兼容版本）
function verifyToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        // 先检查表结构
        $hasTokenField = false;
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM users LIKE 'token'")->fetchAll();
            $hasTokenField = (count($columns) > 0);
        } catch (Exception $e) {
            $hasTokenField = false;
        }
        
        if ($hasTokenField) {
            // 尝试新的token验证
            $sql = "SELECT * FROM users WHERE token = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // 检查用户状态和过期时间
                $isActive = ($user['status'] == 'active' || $user['status'] == 1);
                $isNotExpired = empty($user['token_expires']) || strtotime($user['token_expires']) > time();
                
                if ($isActive && $isNotExpired) {
                    return $user;
                }
                
                // 如果用户存在但token过期，更新过期时间并返回用户（兼容处理）
                if ($isActive) {
                    try {
                        $updateSql = "UPDATE users SET token_expires = DATE_ADD(NOW(), INTERVAL 7 DAY) WHERE id = ?";
                        $updateStmt = $pdo->prepare($updateSql);
                        $updateStmt->execute([$user['id']]);
                        return $user;
                    } catch (Exception $e) {
                        // 更新失败，继续下面的验证
                    }
                }
            }
        }
        
        // 备用方案1：尝试将token作为openid来验证
        $sql = "SELECT * FROM users WHERE openid = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            $isActive = ($user['status'] == 'active' || $user['status'] == 1);
            if ($isActive) {
                return $user;
            }
        }
        
        // 备用方案2：尝试更宽松的状态检查
        $sql = "SELECT * FROM users WHERE (openid = ? OR (token IS NOT NULL AND token = ?)) AND status != 0";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token, $token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            return $user;
        }
        
        return false;
        
    } catch (Exception $e) {
        // 最基础的验证
        try {
            $sql = "SELECT * FROM users WHERE openid = ? LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e2) {
            return false;
        }
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 获取当前用户
function getCurrentUser() {
    $token = getAuthToken();
    if (!$token) {
        error('需要登录', 401);
    }
    
    $user = verifyToken($token);
    if (!$user) {
        error('登录已过期，请重新登录', 401);
    }
    
    return $user;
}

// 获取常用观众信息列表
function getCommonVisitorsList() {
    global $pdo;
    
    $user = getCurrentUser();
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = min(50, max(1, intval($_GET['limit'] ?? 20)));
    $keyword = $_GET['keyword'] ?? '';
    $offset = ($page - 1) * $limit;
    
    try {
        // 构建查询条件
        $whereClause = "WHERE user_id = ?";
        $params = [$user['id']];
        
        if (!empty($keyword)) {
            $whereClause .= " AND (name LIKE ? OR phone LIKE ? OR id_number LIKE ?)";
            $keywordParam = "%$keyword%";
            $params[] = $keywordParam;
            $params[] = $keywordParam;
            $params[] = $keywordParam;
        }
        
        // 查询常用观众信息列表
        $sql = "SELECT * FROM common_visitors 
                $whereClause 
                ORDER BY updated_at DESC 
                LIMIT $limit OFFSET $offset";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $visitors = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) as total FROM common_visitors $whereClause";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // 处理数据格式
        $list = [];
        foreach ($visitors as $visitor) {
            $list[] = [
                'id' => intval($visitor['id']),
                'name' => $visitor['name'],
                'id_type' => $visitor['id_type'],
                'id_number' => $visitor['id_number'],
                'phone' => $visitor['phone'],
                'created_at' => $visitor['created_at'],
                'updated_at' => $visitor['updated_at']
            ];
        }
        
        success([
            'list' => $list,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => intval($total),
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取常用观众信息失败: ' . $e->getMessage(), 500);
    }
}

// 添加常用观众信息
function addCommonVisitor() {
    global $pdo;
    
    $user = getCurrentUser();
    $input = json_decode(file_get_contents('php://input'), true);
    
    // 验证必填字段
    if (empty($input['name'])) {
        error('姓名不能为空');
    }
    
    $name = trim($input['name']);
    $idType = $input['id_type'] ?? '身份证';
    $idNumber = trim($input['id_number'] ?? '');
    $phone = trim($input['phone'] ?? '');
    
    // 验证姓名长度
    if (mb_strlen($name) > 50) {
        error('姓名长度不能超过50个字符');
    }
    
    // 验证手机号格式（如果提供）
    if (!empty($phone) && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
        error('手机号格式不正确');
    }
    
    // 验证身份证号格式（如果是身份证且提供了号码）
    if ($idType === '身份证' && !empty($idNumber)) {
        if (!preg_match('/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $idNumber)) {
            error('身份证号格式不正确');
        }
    }
    
    try {
        // 检查是否已存在相同的观众信息
        $conditions = [];
        $params = [$user['id']];
        
        if (!empty($phone)) {
            $conditions[] = "phone = ?";
            $params[] = $phone;
        }
        
        if (!empty($idNumber)) {
            $conditions[] = "id_number = ?";
            $params[] = $idNumber;
        }
        
        if (!empty($conditions)) {
            $checkSql = "SELECT id, name FROM common_visitors 
                        WHERE user_id = ? AND (" . implode(' OR ', $conditions) . ")";
            $checkStmt = $pdo->prepare($checkSql);
            $checkStmt->execute($params);
            $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($existing) {
                error("该观众信息已存在（姓名：{$existing['name']}）");
            }
        }
        
        // 创建常用观众信息记录
        $insertSql = "INSERT INTO common_visitors 
                     (user_id, name, id_type, id_number, phone, created_at, updated_at)
                     VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
        
        $insertStmt = $pdo->prepare($insertSql);
        $insertStmt->execute([$user['id'], $name, $idType, $idNumber, $phone]);
        
        $visitorId = $pdo->lastInsertId();
        
        success([
            'id' => $visitorId,
            'name' => $name,
            'id_type' => $idType,
            'id_number' => $idNumber,
            'phone' => $phone
        ], '常用观众信息添加成功');
        
    } catch (Exception $e) {
        error('添加常用观众信息失败: ' . $e->getMessage());
    }
}

// 更新常用观众信息
function updateCommonVisitor() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$id) {
        error('观众信息ID不能为空');
    }
    
    try {
        // 检查观众信息是否存在且属于当前用户
        $sql = "SELECT * FROM common_visitors WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $visitor = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$visitor) {
            error('观众信息不存在', 404);
        }
        
        // 构建更新数据
        $updateFields = [];
        $params = [];
        
        if (isset($input['name']) && !empty($input['name'])) {
            $name = trim($input['name']);
            if (mb_strlen($name) > 50) {
                error('姓名长度不能超过50个字符');
            }
            $updateFields[] = "name = ?";
            $params[] = $name;
        }
        
        if (isset($input['id_type'])) {
            $updateFields[] = "id_type = ?";
            $params[] = $input['id_type'];
        }
        
        if (isset($input['id_number'])) {
            $idNumber = trim($input['id_number']);
            // 如果是身份证且不为空，验证格式
            if (($input['id_type'] ?? $visitor['id_type']) === '身份证' && !empty($idNumber)) {
                if (!preg_match('/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $idNumber)) {
                    error('身份证号格式不正确');
                }
            }
            $updateFields[] = "id_number = ?";
            $params[] = $idNumber;
        }
        
        if (isset($input['phone'])) {
            $phone = trim($input['phone']);
            if (!empty($phone) && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
                error('手机号格式不正确');
            }
            $updateFields[] = "phone = ?";
            $params[] = $phone;
        }
        
        if (empty($updateFields)) {
            error('没有需要更新的数据');
        }
        
        $updateFields[] = "updated_at = NOW()";
        $params[] = $id;
        
        $updateSql = "UPDATE common_visitors SET " . implode(', ', $updateFields) . " WHERE id = ?";
        $updateStmt = $pdo->prepare($updateSql);
        $updateStmt->execute($params);
        
        success(null, '常用观众信息更新成功');
        
    } catch (Exception $e) {
        error('更新常用观众信息失败: ' . $e->getMessage());
    }
}

// 删除常用观众信息
function deleteCommonVisitor() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    
    if (!$id) {
        error('观众信息ID不能为空');
    }
    
    try {
        // 检查观众信息是否存在且属于当前用户
        $sql = "SELECT * FROM common_visitors WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $visitor = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$visitor) {
            error('观众信息不存在', 404);
        }
        
        // 删除观众信息
        $deleteSql = "DELETE FROM common_visitors WHERE id = ?";
        $deleteStmt = $pdo->prepare($deleteSql);
        $deleteStmt->execute([$id]);
        
        success(null, '常用观众信息删除成功');
        
    } catch (Exception $e) {
        error('删除常用观众信息失败: ' . $e->getMessage());
    }
}

// 获取常用观众信息详情
function getCommonVisitorDetail() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    
    if (!$id) {
        error('观众信息ID不能为空');
    }
    
    try {
        $sql = "SELECT * FROM common_visitors WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $visitor = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$visitor) {
            error('观众信息不存在', 404);
        }
        
        success([
            'id' => intval($visitor['id']),
            'name' => $visitor['name'],
            'id_type' => $visitor['id_type'],
            'id_number' => $visitor['id_number'],
            'phone' => $visitor['phone'],
            'created_at' => $visitor['created_at'],
            'updated_at' => $visitor['updated_at']
        ]);
        
    } catch (Exception $e) {
        error('获取观众信息详情失败: ' . $e->getMessage(), 500);
    }
}

// 获取常用观众信息统计
function getCommonVisitorStats() {
    global $pdo;
    
    $user = getCurrentUser();
    
    try {
        $sql = "SELECT 
                    COUNT(*) as total_visitors,
                    COUNT(CASE WHEN id_type = '身份证' THEN 1 END) as id_card_count,
                    COUNT(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 END) as phone_count,
                    DATE(MAX(created_at)) as latest_add_date
                FROM common_visitors 
                WHERE user_id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user['id']]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        success([
            'total_visitors' => intval($stats['total_visitors']),
            'id_card_count' => intval($stats['id_card_count']),
            'phone_count' => intval($stats['phone_count']),
            'latest_add_date' => $stats['latest_add_date']
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getCommonVisitorsList();
                    break;
                case 'detail':
                    getCommonVisitorDetail();
                    break;
                case 'stats':
                    getCommonVisitorStats();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'create':
                    addCommonVisitor();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'PUT':
            switch ($action) {
                case 'update':
                    updateCommonVisitor();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'DELETE':
            switch ($action) {
                case 'delete':
                    deleteCommonVisitor();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>